package controller

import (
	"net/http"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func SendError(c *gin.Context, err error) {
	c.String(http.StatusInternalServerError, err.Error())
}

func SendData(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, data)
}

func Serve() {

	router := gin.Default()
	mwCORS := cors.New(cors.Config{
		//准许跨域请求网站,多个使用,分开,限制使用*
		AllowOrigins: []string{"*"},
		//准许使用的请求方式
		AllowMethods: []string{"PUT", "PATCH", "POST", "GET", "DELETE"},
		//准许使用的请求表头
		AllowHeaders: []string{"Origin", "Authorization", "Content-Type"},
		//显示的请求表头
		ExposeHeaders: []string{"Content-Type"},
		//凭证共享,确定共享
		AllowCredentials: true,
		//容许跨域的原点网站,可以直接return true就万事大吉了
		AllowOriginFunc: func(origin string) bool {
			return true
		},
		//超时时间设定
		MaxAge: 24 * time.Hour,
	})
	router.Use(mwCORS)

	// 静态文件
	router.LoadHTMLGlob("resources/static/html/*.html")
	router.StaticFS("/static/", http.Dir("resources/static"))

	// 页面
	router.GET("/", IndexController)
	router.GET("/history", HistoryController)
	router.GET("/detail", DetailController)

	// API
	router.GET("/api/projects", ListProjectsController)
	router.POST("/api/project", CreateProjectController)
	router.POST("/api/workflow", CreateWorkflowController)
	router.POST("/api/trigger", TriggerWorkflowController)
	router.GET("/api/history", ListHistoryController)
	router.GET("/api/detail", ShowDetailController)
	router.GET("/api/workflow", GetWorkflowController)

	router.Run(":8081")
}
